<?php
/*
 * Log Deliver
 */
class Logger
{
	const _CONST_LOCAL_LOG_ADDR_  = 'tcp://127.0.0.1:9999';
	const _CONST_SEPARATING_LINE_ = '-----JLDSF232SFLFJ%3432-----';
	const _CONST_SERVICE_DEFAULT_ = 1;
	private static $_instance = NULL;
	private $_socket   = FALSE;
	private $_log_list = array();

	/**
	 * log event
	 *
	 * @param   int      $uid   : user passport UID
	 * @param   int	     $do    : event_type
	 * @param   string   $do_arg: arguments for event_type
	 * @param   int      $where : where_type
	 * @param   string   $w_arg : arguments for where_type
	 * @param   char(15) $ip    : user ip address
	 * @param   int	     $time  : event time [optional]
	 * @param	int		 $service: service type, ie: mydellclub, ...
	 * @return  void
	 */
	public static function add ($uid, $do, $do_arg, $where, $where_arg, $ip, $time = NULL, $service = NULL)
	{
		if (empty($time))
			$time = time();

		if (empty($service))
			$service = self::_CONST_SERVICE_DEFAULT_;

		$log = array(
			'uid'    => (int) $uid,
			'do'     => (int) $do,
			'where'  => (int) $where,
			'time'   => (int) $time,
			'service'=> (int) $service,
			'do_arg'    => trim($do_arg),
			'where_arg' => trim($where_arg),
			'ip'        => trim($ip),
		);

		self::instance()->log($log);
	}

	private static function instance ()
	{
		if (NULL === self::$_instance)
		{
			$class = __CLASS__;
			self::$_instance = new $class();
		}

		return self::$_instance;
	}

	private function __construct () 
	{
		$this->_socket = stream_socket_client(self::_CONST_LOCAL_LOG_ADDR_);
	}

	private function log (& $log)
	{
		$this->_log_list[] = $this->build_log_content($log);
	}

	private function deliver ()
	{
		if ($this->_socket)
		{
			$content = join(self::_CONST_SEPARATING_LINE_, $this->_log_list);
			fwrite($this->_socket, $content);
		}
	}

	private function build_log_content (& $log)
	{
		return base64_encode(json_encode($log));
	}

	public function __destruct ()
	{
		if ($this->_socket)
		{
			$this->deliver();

			fclose($this->_socket);
		}
	}
}
